
import React, { useState, useEffect, useCallback } from "react";
import { OperationalUnit } from "@/entities/OperationalUnit";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Plus, Building, Users, Wrench } from "lucide-react";
import { useToast } from "@/components/ui/use-toast";

import OperationalUnitForm from "../operational-units/OperationalUnitForm";
import OperationalUnitCard from "../operational-units/OperationalUnitCard";

export default function OperationalUnitsManager() {
  const [units, setUnits] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editingUnit, setEditingUnit] = useState(null);
  const { toast } = useToast();

  const loadUnits = useCallback(async () => {
    setIsLoading(true);
    try {
      const fetchedUnits = await OperationalUnit.list("-created_date");
      setUnits(Array.isArray(fetchedUnits) ? fetchedUnits : []);
    } catch (error) {
      console.error("加载作业单位失败:", error);
      toast({
        variant: "destructive",
        title: "加载失败",
        description: "无法加载作业单位数据"
      });
      setUnits([]);
    }
    setIsLoading(false);
  }, [toast]); // Add toast as a dependency for useCallback

  useEffect(() => {
    loadUnits();
  }, [loadUnits]); // Add loadUnits as a dependency for useEffect

  const handleSubmit = async (unitData) => {
    try {
      if (editingUnit) {
        await OperationalUnit.update(editingUnit.id, unitData);
        toast({
          title: "更新成功",
          description: "作业单位已更新"
        });
      } else {
        await OperationalUnit.create(unitData);
        toast({
          title: "创建成功",
          description: "作业单位已创建"
        });
      }
      setShowForm(false);
      setEditingUnit(null);
      await loadUnits();
    } catch (error) {
      console.error("保存单位失败:", error);
      toast({
        variant: "destructive", 
        title: "保存失败",
        description: error.message || "未知错误"
      });
    }
  };

  const handleEdit = (unit) => {
    setEditingUnit(unit);
    setShowForm(true);
  };

  const handleDelete = async (unitId) => {
    if (window.confirm("确定要删除此作业单位吗？")) {
      try {
        await OperationalUnit.delete(unitId);
        toast({
          title: "删除成功",
          description: "作业单位已删除"
        });
        await loadUnits();
      } catch (error) {
        console.error("删除单位失败:", error);
        toast({
          variant: "destructive",
          title: "删除失败",
          description: error.message || "未知错误"
        });
      }
    }
  };

  const handleCancel = () => {
    setShowForm(false);
    setEditingUnit(null);
  };

  const getUnitsByType = (type) => units.filter(u => u.type === type);

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h3 className="text-xl font-semibold">作业单位管理</h3>
          <p className="text-gray-600 mt-1">管理施工单位、设计单位和监理单位的资源配置</p>
        </div>
        <Button
          onClick={() => setShowForm(true)}
          className="bg-blue-600 hover:bg-blue-700"
        >
          <Plus className="w-4 h-4 mr-2" />
          添加单位
        </Button>
      </div>

      {/* Statistics */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card className="bg-gradient-to-r from-blue-50 to-blue-100 border-blue-200">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-blue-600">施工单位</p>
                <p className="text-2xl font-bold text-blue-700">
                  {getUnitsByType('construction_unit').length}
                </p>
              </div>
              <Building className="w-8 h-8 text-blue-500" />
            </div>
          </CardContent>
        </Card>

        <Card className="bg-gradient-to-r from-green-50 to-green-100 border-green-200">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-green-600">设计单位</p>
                <p className="text-2xl font-bold text-green-700">
                  {getUnitsByType('design_unit').length}
                </p>
              </div>
              <Wrench className="w-8 h-8 text-green-500" />
            </div>
          </CardContent>
        </Card>

        <Card className="bg-gradient-to-r from-purple-50 to-purple-100 border-purple-200">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-purple-600">监理单位</p>
                <p className="text-2xl font-bold text-purple-700">
                  {getUnitsByType('supervision_unit').length}
                </p>
              </div>
              <Users className="w-8 h-8 text-purple-500" />
            </div>
          </CardContent>
        </Card>
      </div>

      {showForm && (
        <OperationalUnitForm
          unit={editingUnit}
          onSubmit={handleSubmit}
          onCancel={handleCancel}
        />
      )}

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {isLoading ? (
          Array(4).fill(0).map((_, i) => (
            <Card key={i} className="animate-pulse">
              <CardHeader>
                <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                <div className="h-3 bg-gray-200 rounded w-1/2"></div>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  <div className="h-3 bg-gray-200 rounded"></div>
                  <div className="h-3 bg-gray-200 rounded w-2/3"></div>
                </div>
              </CardContent>
            </Card>
          ))
        ) : units.length === 0 ? (
          <div className="col-span-full">
            <Card className="text-center py-12">
              <CardContent>
                <Building className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                <h3 className="text-lg font-semibold text-gray-900 mb-2">
                  暂无作业单位
                </h3>
                <p className="text-gray-500 mb-6">
                  添加施工单位、设计单位或监理单位来管理资源配置
                </p>
                <Button
                  onClick={() => setShowForm(true)}
                  className="bg-blue-600 hover:bg-blue-700"
                >
                  <Plus className="w-4 h-4 mr-2" />
                  添加单位
                </Button>
              </CardContent>
            </Card>
          </div>
        ) : (
          units.map((unit) => (
            <OperationalUnitCard
              key={unit.id}
              unit={unit}
              onEdit={handleEdit}
              onDelete={handleDelete}
            />
          ))
        )}
      </div>
    </div>
  );
}
